import 'dart:convert';
import 'package:aitao_flutter/const/common_const.dart';
import 'package:aitao_flutter/im/im_pay_tool.dart';
import 'package:aitao_flutter/res/r.dart';
import 'package:aitao_flutter/routes/routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nim_chatkit_ui/chat_page.dart';
import 'package:nim_core/nim_core.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../model/im/video_chat_model.dart';
import '../../model/personal_model.dart';
import '../../model/user_data.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../utils/sp_utils.dart';

class PersonalController extends GetxController {
  int userId = 0;
  UserData? userData;
  PersonalModel? personalModel;
  List<String> dynamicsList = [];
  List<String> giftList = [];
  List<String> guardList = [];
  @override
  void onInit() {
    super.onInit();
    if (Get.parameters.isNotEmpty) {
      userId = int.parse(Get.parameters['userId'].toString());
      getUserInfoData();
      getLocalUserData();
    }
  }

  void getLocalUserData() async {
    userData = SpUtil.getUserData();
  }

  /// 打招呼文本
  void greetTextClick(String greetText) async {
    debugPrint('文本打招呼:$greetText');
    IMPayTool.sendMessageFilter(
        NIMMessageType.text, greetText, userId.toString(),
        (type, filter, content) {
      debugPrint('发消息接口验证成功');
      debugPrint('type:$type');
      debugPrint('filter:$filter');
      debugPrint('content:$content');
      if (filter == 0) {
        IMPayTool.sendTextMessage(userId.toString(), content);
      } else {
        IMPayTool.sendTextMessage(userId.toString(), content);
      }
    });
  }

  /// 打招呼图片
  void greetImageClick(BuildContext context, int greetImageId) async {
    IMPayTool.sendGreetImage(userId.toString(), greetImageId, () {
      debugPrint('打招呼图片');
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return ChatPage(
            sessionId: personalModel!.info!.usercode.toString(),
            sessionType: NIMSessionType.p2p);
      }));
    });
  }

  /// 打招呼语音
  void greetVoiceClick(BuildContext context, int greetVoiceId) async {
    IMPayTool.sendGreetVoice(userId.toString(), greetVoiceId, () {
      debugPrint('打招呼语音');
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return ChatPage(
            sessionId: personalModel!.info!.usercode.toString(),
            sessionType: NIMSessionType.p2p);
      }));
    });
  }

  /// 删除打招呼
  void deleteGreetVoice(int greetVoiceId) async {
    var result = await RequestManager()
        .post(API.deleteHelloVoice, params: {'hi_id': greetVoiceId});
    debugPrint('删除打招呼');
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast('删除成功');
    }
  }

  /// 私聊
  void chatClick(BuildContext context) {
    if (personalModel != null &&
        personalModel!.info != null &&
        personalModel!.info!.usercode != null) {
      Navigator.push(context, MaterialPageRoute(builder: (context) {
        return ChatPage(
            sessionId: personalModel!.info!.usercode.toString(),
            sessionType: NIMSessionType.p2p);
      }));
    }
  }

  /// 赠送礼物
  void sendGift(int giftId) async {
    if (giftId == 0) return;
    var result = await RequestManager().post(API.sendGift,
        params: {'num': 1, 'type': 1, 'to_uid': userId, 'gift_id': giftId});
    debugPrint('礼物赠送结果');
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast('礼物赠送成功');
    }
  }

  /// 守护主播
  void sendGuard(int guardNum) async {
    var result = await RequestManager()
        .post(API.addGuard, params: {'user_id': userId, 'guard_num': guardNum});
    debugPrint('守护赠送结果');
    if (result != null && result['code'] == 0) {
      EasyLoading.showToast('礼物赠送成功');
    }
  }

  /// 获取用户主页信息
  void getUserInfoData() async {
    var result = await RequestManager()
        .post(API.userHomeData, params: {'user_id': userId});
    if (result != null && result['code'] == 0) {
      personalModel = PersonalModel.fromJson(result['data']);
      // 处理数据
      // 动态只取前面2条
      if (personalModel?.dynamicImgs != null) {
        for (int i = 0; i < personalModel!.dynamicImgs!.length; i++) {
          if (i == 2) break;
          dynamicsList.add(personalModel!.dynamicImgs![i]);
        }
      }
      // 礼物只取前面4个
      if (personalModel?.gifts != null) {
        for (int i = 0; i < personalModel!.gifts!.length; i++) {
          if (i == 4) break;
          giftList.add(personalModel!.gifts![i].img ?? '');
        }
      }
      // 守护只取前面4个
      if (personalModel?.guard != null) {
        for (int i = 0; i < personalModel!.guard!.list!.length; i++) {
          if (i == 4) break;
          guardList.add(personalModel!.guard!.list![i]);
        }
      }
      update();
    }
  }

  // 是否自己的主页
  bool isMinePage() {
    return userData?.userinfo?.usercode == personalModel?.info?.usercode;
  }

  // 关注 && 取消关注
  void focusClick() async {
    var result = await RequestManager().post(API.followUser,
        params: {'follow_uid': personalModel?.info?.userid});
    if (result != null && result['code'] == 0) {
      personalModel?.info?.isFollow =
          personalModel?.info?.isFollow == 0 ? 1 : 0;
      update();
    }
  }

  String setVipIcon() {
    if (personalModel == null) return '';
    if (personalModel!.info == null) return '';
    if (personalModel!.info!.vip == 0 && personalModel!.info!.vipLevel == 1) {
      return ImagePath.assetsImagesGoldVip3; //黄金单月
    }
    if (personalModel!.info!.vip == 0 && personalModel!.info!.vipLevel == 2) {
      return ImagePath.assetsImagesGoldVip2; //黄金季度
    }
    if (personalModel!.info!.vip == 0 && personalModel!.info!.vipLevel == 3) {
      return ImagePath.assetsImagesGoldVip1; //黄金永久
    }
    if (personalModel!.info!.vip == 1 && personalModel!.info!.vipLevel == 1) {
      return ImagePath.assetsImagesDiamondVip3; //钻石单月
    }
    if (personalModel!.info!.vip == 1 && personalModel!.info!.vipLevel == 2) {
      return ImagePath.assetsImagesDiamondVip2; //钻石季度
    }
    if (personalModel!.info!.vip == 1 && personalModel!.info!.vipLevel == 3) {
      return ImagePath.assetsImagesDiamondVip3; //钻石永久
    }
    return '';
  }

  void routerClick(String title) {
    if (title == '举报') {
      Get.toNamed(Routes.reportPage, parameters: {
        'type': '1',
        'reportUid': (personalModel?.info?.userid ?? 0).toString()
      });
    } else if (title == '礼物列表') {
      Get.toNamed(Routes.giftListPage, parameters: {
        'userId': (personalModel?.info?.userid ?? 0).toString()
      });
    }
  }

  // 视频通话前判断相机的权限
  void videoCheckCameraPermission() async {
    var cameraStatus = await Permission.camera.status;
    if (cameraStatus == PermissionStatus.granted) {
      // Get.toNamed(Routes.videoChatPage);

      // 发起请求
      var result = await RequestManager()
          .post(API.videoCall, params: {'to_uid': userId});
      if (result != null && result['code'] == 0) {
        // debugPrint('获取通话信息');
        // WJLogUtils.wjLog(result);
        VideoChatModel model = VideoChatModel.fromJson(result['data']);
        Get.toNamed(Routes.videoChatPage,
            parameters: {
              'model': json.encode(model),
              'type': ChatStringConst.videoRequestPage
            },
            preventDuplicates: false);
      }
    } else if (cameraStatus == PermissionStatus.denied) {
      await Permission.camera.request();
    } else {
      EasyLoading.showToast('没有相机权限!!');
    }
  }
}
